package com.example.yls.demoa;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by yls on 2018/12/17.
 */

public class MyService extends Service{
    private boolean isLive=true;
    private String timeStr;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        throw  new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("MyService","thread id = "+Thread.currentThread().getId());

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isLive) {
                    Intent intent = new Intent();
                    intent.setAction("TIME_CHANGE");
                    intent.putExtra("time", getTimeStr());
                    sendBroadcast(intent);

                    try{
                       Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    //获取当前时间的字符串
    public String getTimeStr() {
        Date date=new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        return format.format(date);
    }

    @Override
    public void onDestroy() {
        isLive=false;
        super.onDestroy();
    }
}
